package com.wujilee.orderservice.controller;

import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.nativepay.model.Transaction;
import com.wujilee.dbentity.entity.EntityOrderInfo;
import com.wujilee.orderservice.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.stream.Collectors;

/**
 * @author liwuji
 * @date 2024/6/17
 * @desc
 **/
@RestController
@RequestMapping("/pay")
@Slf4j 
public class PayController {
    @Resource
    private OrderService orderService;
    @Resource
    private NotificationParser notificationParser;
    @PostMapping
    public String pay(@RequestBody EntityOrderInfo entityOrderInfo){
        return orderService.pay(entityOrderInfo.getId());
    }

    /**
     * 微信支付回调接口
     * @param request
     * @return
     */
    @PostMapping("/weixin/native/notify")
    public ResponseEntity.BodyBuilder notify(HttpServletRequest request) throws IOException {
        String wechatSignature = request.getHeader("Wechatpay-Signature");
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");
        String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
        // 构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(wechatpayNonce)
                .signature(wechatSignature)
                .timestamp(wechatTimestamp)
                .body(request.getReader().lines().collect(Collectors.joining(System.lineSeparator())))
                .build();
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
            orderService.notifyOrder(transaction);
        } catch (ValidationException e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            log.error("sign verification failed", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED);
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return ResponseEntity.status(HttpStatus.OK);
    }
    
}
